package com.zte.warehouse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zte.market.model.MarketOrderCondition;
import com.zte.market.model.MarketOrderdetails;
import com.zte.market.model.MarketOrders;
import com.zte.util.PageModel;
import com.zte.warehouse.dao.IOutWarehouseDao;
import com.zte.warehouse.model.*;
import com.zte.warehouse.service.IInWarehouseService;
import com.zte.warehouse.service.IOutWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OutWarehouseService implements IOutWarehouseService {

    @Autowired
    private IOutWarehouseDao iIOutWarehouseDao;


    //    分页查询
    @Override
    public PageModel<OutWarehose> queryOutWarehoseListByCondition(PageModel<OutWarehose> pageModel, OutWarehouseCondition conn) {
        int pageNum = pageModel.getPageNum() <= 0 ? 1 : pageModel.getPageNum();
        int pageSize = pageModel.getPageSize() <= 0 ? 3 : pageModel.getPageSize();

        PageHelper.startPage(pageNum, pageSize);
        List<OutWarehose> OutWarehoses = iIOutWarehouseDao.queryOutWarehoseListByCondition(conn);
        PageInfo<OutWarehose> info = new PageInfo<OutWarehose>(OutWarehoses);

        pageModel.setPageNum(info.getPageNum());
        pageModel.setPageSize(info.getPageSize());
        pageModel.setTotalPage(info.getPages());
        pageModel.setTotalCount((int) info.getTotal());
        pageModel.setData(new ArrayList<OutWarehose>(info.getList()));
        return pageModel;
    }

    //    添加出库
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public int OutWarehoseAdd(OutWarehoseAdd outWarehoseAdd) {
        MarketOrders marketOrders = new MarketOrders();
        marketOrders.setOrderid(outWarehoseAdd.getIndent());
        marketOrders.setDdState(1);
        int i = iIOutWarehouseDao.updateOrder(marketOrders);//防止重复订单出库
        return iIOutWarehouseDao.OutWarehoseAdd(outWarehoseAdd);
    }

    //验证订单审核状态
    @Override
    public MarketOrders queryOrderState(String indent) {
        return iIOutWarehouseDao.queryOrderState(indent);
    }


        @Override
    public List<MarketOrders> testFunction(MarketOrderCondition con) {
//            List<MarketOrders> marketOrders = iIOutWarehouseDao.queryOrdersByCondition(con);
            return null;

    }
//
    // 商品出库
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public int updateOutWarehose(OutWarehouseUpdateCondition con) {
        System.out.println("con:" + con);
        String NewState = con.getNewState();//当前新状态
        System.out.println("NewState:" + NewState);//获取订单新状态
        String Oldstate = con.getState();
        System.out.println("OldState:" + Oldstate);//获取订单原状态

        //!查询订单、订单详情   OrderId  count（据OrderId获取）
        MarketOrderCondition marketOrderCondition = new MarketOrderCondition();
        marketOrderCondition.setOrderid(con.getOrderid());
        List<MarketOrders> marketOrders = iIOutWarehouseDao.queryOrdersByCondition(marketOrderCondition);//当前订单详情
        System.out.println(marketOrders);
//        List<MarketOrderdetails> orderdetails = marketOrders.get(1).getOrderdetails();

        StockInsert stockInsert = new StockInsert();
        List<StockInsert> stockMessage = iIOutWarehouseDao.queryStockMessage(con.getOrderid());//订单所需库存商品信息
        System.out.println("stockMessage:" + stockMessage);

        int result=-1;
        boolean flag=true;
        Double lastmaoney=0d;
        SingleWarehouse singleWarehouse = iIOutWarehouseDao.selectWarehose(con.getWarehouseID());//当前订单仓库
        System.out.println(singleWarehouse);
        if (Oldstate.equals("1")&&NewState.equals("5")) {//直接退货  1->5
            result = updateOutWarehoseState("5", con.getOrderid());
        }
        if (NewState.equals("2")) {//发货:库存检查,减库存  1->2
            //!查询对应仓库库中是否充足  WarehouseID,productId    ，count ，充足更新状态，添加金额    不足提示
            for (int j = 0; j < stockMessage.size(); j++) {//充足，发货，减去库存
                int lastCount=stockMessage.get(j).getRepertory()-marketOrders.get(j).getOrderdetails().get(0).getPurchaseNum();
                if(lastCount>0) {
                    stockInsert.setRepertory(lastCount);//库存商品数量增加
                    stockInsert.setWarehouseId(con.getWarehouseID());
                    stockInsert.setProductId(marketOrders.get(j).getOrderdetails().get(0).getProductId());
                    iIOutWarehouseDao.updateIsStock(stockInsert);  //!更新库存商品数量
                }else {
                    flag=false;
                    break;
                }
            }
            result = updateOutWarehoseState("2", con.getOrderid());
        }
        if (NewState.equals("3")) {//已回款:更新仓库账面金额 2->3
            lastmaoney=singleWarehouse.getWMoney()+marketOrders.get(0).getOrdermoney();
            updateWarehoseMoney(lastmaoney,con.getWarehouseID());
            result = updateOutWarehoseState("3", con.getOrderid());
        }
        if (NewState.equals("4")) {//取消订单 ， 更新仓库账面金额
            if (Oldstate.equals("1")) {//1->4  ！！未发货取消，更新状态为5已退货
                result = updateOutWarehoseState("5", con.getOrderid());
            }
            if (Oldstate.equals("2")) {//2->4  已发货取消，更新状态为4取消订单
                result = updateOutWarehoseState("4", con.getOrderid());
            }
        }
        if (Oldstate.equals("4")&&NewState.equals("5")) {//确认已退货:更新仓库账面金额 4->5
            lastmaoney=singleWarehouse.getWMoney()-marketOrders.get(0).getOrdermoney();
            updateWarehoseMoney(lastmaoney,con.getWarehouseID());//退款
            for (int j = 0; j < stockMessage.size(); j++) {
                stockInsert.setRepertory(marketOrders.get(j).getOrderdetails().get(0).getPurchaseNum()+ stockMessage.get(j).getRepertory());//库存商品数量增加
                stockInsert.setWarehouseId(con.getWarehouseID());
                stockInsert.setProductId(marketOrders.get(j).getOrderdetails().get(0).getProductId());
                iIOutWarehouseDao.updateIsStock(stockInsert);  //退货  !更新库存商品数量
            }
            result = updateOutWarehoseState("5", con.getOrderid());
        }
        if(!flag){result=-2;}//库存不足
        return result;
    }

    public int updateOutWarehoseState(String newState, String indent) {
        //更新出库表操作状态  orderId    state 5/4/3/2/1
        OutWarehoseAdd outWarehoseAdd = new OutWarehoseAdd();
        outWarehoseAdd.setState(newState);
        outWarehoseAdd.setIndent(indent);
        int i1 = iIOutWarehouseDao.updateOutWarehose(outWarehoseAdd);
        System.out.println("outWarehoseAdd:" + outWarehoseAdd);
        System.out.println("i1:" + i1);
        return i1;
    }

    public int updateWarehoseMoney(Double wmoney, int wid) {
        //更新仓库账面金额   WarehouseID  lastWmoney
        SingleWarehouse singleWarehouse = new SingleWarehouse();
        singleWarehouse.setId(wid);
        singleWarehouse.setWMoney(wmoney);
        int i2 = iIOutWarehouseDao.updateWarehose(singleWarehouse);
        System.out.println("singleWarehouse:" + singleWarehouse);
        System.out.println("i2:" + i2);
        return i2;
    }


}
